// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    currentTab: 'knowledge',
    tabItems: [
      { id: 'knowledge', name: '常识判断' },
      { id: 'language', name: '言语理解' },
      { id: 'quantity', name: '数量关系' },
      { id: 'logic', name: '判断推理' }
    ],
    examList: [],
    loading: false,
    banners: [
      {
        id: 1,
        imageUrl: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.QXTd8lTGERqM0NdNIXajtgHaEK?w=189&h=106&c=7&r=0&o=5&dpr=1.8&pid=1.7',
        title: '2025国考备考专题'
      },
      {
        id: 2,
        imageUrl: 'https://tse1-mm.cn.bing.net/th/id/OIP-C.LKBlSo1FGUtbo6kzvyDw2wHaEK?w=189&h=106&c=7&r=0&o=5&dpr=1.8&pid=1.7',
        title: '省考考试技巧分享'
      },
      {
        id: 3,
        imageUrl: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.np98xGZoYD7Q-xU4prgYCwHaDJ?w=312&h=148&c=7&r=0&o=5&dpr=1.8&pid=1.7',
        title: '事业单位考试攻略'
      }
    ],
    background: [
      '/images/banner1.jpg',
      '/images/banner2.jpg',
      '/images/banner3.jpg'
    ],
    features: [
      { icon: 'newspaper-o', text: '近期热点', url: '/pages/topics/topics' },
      { icon: 'todo-list-o', text: '历年真题', url: '/pages/pastexams/pastexams' },
      { icon: 'clock-o', text: '考试倒计时', url: '/pages/countdown/countdown' },
      { icon: 'notes-o', text: '错题收藏', url: '/pages/mistakes/mistakes' }
    ]
  },
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onLoad: function (options) {
    this.loadExamList('quantity');
  },
  onReady() {
    // 尝试修复滚动问题
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
  },
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().init();
    }
  },
  onTabChange(event) {
    console.log('Tab切换事件:', event.detail);
    const category = event.detail.name;  // van-tabs 组件的事件detail中包含name属性
    this.setData({
      currentTab: category,
      examList: []
    });
    this.loadExamList(category);
  },
  loadExamList: function (category) {
    const examApi = require('../../utils/examApi.js');
    
    this.setData({ loading: true });
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    console.log('获取试卷参数:', { category });

    examApi.getExamPapers({ category })
      .then(response => {
        console.log('获取到的考试列表:', response);
        const data = response.records || [];
        this.setData({
          examList: data,
          loading: false
        });
      })
      .catch(error => {
        console.error('获取考试列表失败:', error);
        wx.showToast({
          title: '获取考试列表失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  getTabNameByID: function(tabID) {
    const tab = this.data.tabItems.find(item => item.id === tabID);
    return tab ? tab.name : '';
  },
  
  // 更多功能
  viewMore: function() {
    wx.navigateTo({
      url: '/pages/exammore/exammore'
    });
  },
  
  // 开始答题
  startExam: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exam/index?id=${id}`
    });
  },

  // 查看考试成绩
  viewExamResult: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exam-result/index?id=${id}`
    });
  },

  navigateToCompetition() {
    wx.navigateTo({
      url: '/pages/competition/index'
    });
  },
  navigateToSpecialExam() {
    wx.navigateTo({
      url: '/pages/special-exam/index'
    });
  },
  navigateToMistakes() {
    wx.navigateTo({
      url: '/pages/mistakes/index'
    });
  },
  navigateToForum() {
    console.log('跳转到考试论坛');
    wx.switchTab({
      url: '/pages/forum/index',
      success: () => {
        console.log('成功跳转到论坛页面');
      },
      fail: (error) => {
        console.error('跳转到论坛页面失败:', error);
        // 显示错误提示
        wx.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  navigateToMoreExams() {
    wx.navigateTo({
      url: '/pages/more-exams/index'
    });
  },
  onBannerTap(e) {
    const bannerId = e.currentTarget.dataset.id;
    console.log('点击了轮播图:', bannerId);
    // 根据bannerId跳转到不同页面
    switch(bannerId) {
      case 1:
        wx.navigateTo({
          url: '/pages/special-exam/index'
        });
        break;
      case 2:
        wx.navigateTo({
          url: '/pages/competition/index'
        });
        break;
      case 3:
        wx.navigateTo({
          url: '/pages/forum/index'
        });
        break;
      default:
        break;
    }
  },
  startExam(e) {
    const examId = e.currentTarget.dataset.id;
    console.log('开始答题，试卷ID:', examId);
    
    if (!examId) {
      wx.showToast({
        title: '试卷ID不能为空',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.navigateTo({
      url: `/pages/exam/index?examId=${examId}`,
      success: () => {
        console.log('成功跳转到答题页面');
        wx.hideLoading();
      },
      fail: (error) => {
        console.error('跳转失败:', error);
        wx.hideLoading();
        wx.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  viewExamResult(e) {
    const examId = e.currentTarget.dataset.id;
    console.log('首页点击查看成绩，ID:', examId);
    
    // 显示加载提示
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 直接跳转到submit页面
    wx.navigateTo({
      url: `/pages/submit/index?examId=${examId}`,
      success: () => {
        console.log('成功跳转到成绩页面');
        wx.hideLoading();
      },
      fail: (error) => {
        console.error('跳转失败:', error);
        wx.hideLoading();
        
        // 尝试使用redirectTo作为备选
        wx.redirectTo({
          url: `/pages/submit/index?examId=${examId}`,
          success: () => {
            console.log('redirectTo跳转成功');
          },
          fail: (err) => {
            console.error('所有跳转方式都失败:', err);
            
            // 尝试使用reLaunch作为最后的备选
            wx.reLaunch({
              url: `/pages/submit/index?examId=${examId}`,
              success: () => {
                console.log('reLaunch跳转成功');
              },
              fail: (finalErr) => {
                console.error('所有跳转方法都失败:', finalErr);
                wx.showToast({
                  title: '跳转失败，请重试',
                  icon: 'none'
                });
              }
            });
          }
        });
      }
    });
  }
})
